package com.example.woke;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.http.HttpMethods;
import com.kspay.DateUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.data.Datas_nocardback;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;
import java.util.Random;

public class MywalletcardActivity extends Activity implements OnClickListener {

    private EditText  mEphone;
    private TextView mEname,mEsfz;
    private TextView mTok;
    private EditText mEcvv, mEvalidthru, mEvalidthru1;
    private EditText mEcode;
    private Map<String, String> bankcardtoyeepay;
    //	private ArrayList<String> cardlist;
    private TextView mTbank;
    private boolean isxinyongka;
    private String psdnIp;
    private String times;
    private RelativeLayout mBar;
    private RelativeLayout mSlsd, mSlsd1;
    private EditText mEno;
    private MyApp application;
    private RelativeLayout mRzhihang;
    private String czhiortxian;//�жϳ�ֵ��������
    private ArrayList<String> banklist = new ArrayList<String>();
    private Intent intent;
    private String idCard;

     AlertDialog alertDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mywalletcard);

        intent = getIntent();
//		cardlist = intent.getStringArrayListExtra("cardno");
//		Log.e("cardlist", ""+cardlist);
        psdnIp = Intentnet.getPsdnIp();
        application = (MyApp) getApplication();
        czhiortxian = intent.getStringExtra("czhiortxian");
        idCard = intent.getStringExtra("idcard");
        intview();
    }

    private void intview() {
        findViewById(R.id.avmywalletcard_image_back).setOnClickListener(this);
        mTok = (TextView) findViewById(R.id.avmywalletcard_blind_ok);
        mTok.setOnClickListener(this);
        mEno = (EditText) findViewById(R.id.avmywalletcard_blind_editno);
        mEname = (TextView) findViewById(R.id.avmywalletcard_blind_name);
        mEsfz = (TextView) findViewById(R.id.avmywalletcard_blind_sfz);
        mTbank = (TextView) findViewById(R.id.avmywalletcard_blind_whcihbank);
//		mEcarno = (TextView) findViewById(R.id.avmywalletcard_blind_cardno);
        mEphone = (EditText) findViewById(R.id.avmywalletcard_blind_phone);
        mRzhihang = (RelativeLayout) findViewById(R.id.avmywalletcard_blind_yepaymore);
        mRzhihang.setOnClickListener(this);
        mEcvv = (EditText) findViewById(R.id.avmywalletcard_blind_cvv);
        mEvalidthru = (EditText) findViewById(R.id.avmywalletcard_blind_validthru);
        mEvalidthru1 = (EditText) findViewById(R.id.avmywalletcard_blind_validthru1);
        mEcode = (EditText) findViewById(R.id.avmywalletcard_blind_phonecode);
        mBar = (RelativeLayout) findViewById(R.id.avmywallet_progr_bar);
        mSlsd = (RelativeLayout) findViewById(R.id.avmywall_bank_wehls);
        mSlsd1 = (RelativeLayout) findViewById(R.id.avmywall_bank_wehls1);

        MyApp myApp = MyApp.getInstance();
        Datas_load datas_load = myApp.getDatas_load();
        Log.e("bindcard",""+datas_load.toString());
        if (datas_load != null) {
            mEname.setText(datas_load.getUser_nicename());
            mEsfz.setText(datas_load.getUser_no());
//            if (!(idCard==null||idCard.equals(""))){
//                mEsfz.setText(idCard);
//            }
        }
        mEno.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Log.e("hasFocus","hasFocus");
                } else {
                    String trim = mEno.getText().toString().trim();
                    if (trim.length() > 10) {
                        Log.e("hasFocus",""+trim.length());
                        getcardinfo(trim);

                    }
                }
            }
        });

    }

    private void getcardinfo(final String cardno1) {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(
                MywalletcardActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        //接口信息
        params.put("g", "api");
        params.put("m", "YeePay");
        params.put("a", "queryCardInfo");
        params.put("cardno", cardno1);

        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println(statusCode);
                Log.e("银行卡查询", "response" + response);
                try {
                    String flag = response.getString("flag");
                    String info = response.getString("info");
                    if (flag.equals("success")) {
                        JSONObject jsonObject = response.getJSONObject("data");
                        JSONObject json = jsonObject.getJSONObject("data");
                        System.out.println(json);
                        String cardtype = json.getString("cardtype");// ����

                        if (cardtype.equals("2")) {
                            mSlsd.setVisibility(View.VISIBLE);
                            mSlsd1.setVisibility(View.VISIBLE);
//							mRzhihang.setVisibility(View.GONE);
                            isxinyongka = true;
                        } else {
                            mSlsd.setVisibility(View.GONE);
                            mSlsd1.setVisibility(View.GONE);
                            isxinyongka = false;
                        }
                        String list_bankno = json.getString("cardno");// ��hao
                        Log.e("list_bankno", list_bankno);
                        String list_bankname = json.getString("bankname");// ����
                        String isvalid = json.getString("isvalid");// �Ƿ���Ч��
                        mTbank.setText(list_bankname);
                        Log.e("list_bankname",list_bankname + "========-------------------------");
//						String substring = cardno.substring(
//								(cardno.length() - 4), cardno.length());

                        if (isvalid.equals("0")) {
                            Toast.makeText(MywalletcardActivity.this,
                                    "无效的银行卡", Toast.LENGTH_SHORT).show();
                            mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
                            mTok.setClickable(false);
                        } else {
                            mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
                            mTok.setClickable(true);
                        }
                    } else if (flag.equals("unknow")) {
                        tishi(info);
//                        Toast.makeText(MywalletcardActivity.this,
//                                "" + info, Toast.LENGTH_SHORT).show();
                        mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
                        mTok.setClickable(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                // Log.e("��", "ʧ��" + responseString);
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
//				mBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinish() {
                super.onFinish();
//				mBar.setVisibility(View.GONE);
            }
        });
    }

    private void bankcardto(final String name, final String sfz, final String cardno, final String cvv,
                            final String youxiaoqi, final String youxiaoqi1, final String phone, final String bank) {
        if (application.getDatas_load() == null) return;
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(
                MywalletcardActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "bankList");
        params.put("a", "addCard");
        params.put("user_id", application.getDatas_load().getId());
        params.put("name", name);
        params.put("idcardno", sfz);
        params.put("cardno", cardno);
        params.put("brname", bank);//֧��ȫ��
        params.put("phone", phone);
        params.put("code", cvv);//卡背后三位
        if (isxinyongka == true) {  //2 信用卡
            params.put("cardType", "0");//0Ϊ���ÿ� 1Ϊ���
        } else {
            // 储蓄卡
            params.put("cardType", "1");
        }
        params.put("validthru", youxiaoqi + youxiaoqi1);//���ÿ���Ч��
//		Log.e(application.getuserid(), application.getuserid());
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
				 Log.e("bankcardto", "response"+response);
                try {
                    String flag = response.getString("flag");
                    String info = response.getString("info");
                    if (flag.equals("unknow")) {
                        Toast.makeText(MywalletcardActivity.this, "" + info, Toast.LENGTH_SHORT).show();
                    } else if (flag.equals("success")) {
                        Toast.makeText(MywalletcardActivity.this, "" + info, Toast.LENGTH_SHORT).show();
                        if (czhiortxian.equals("chongzhi")) {
                            //�������֤�����š��ֻ�����
//							banklist.add(name);banklist.add(sfz);banklist.add(cardno);
//							banklist.add(phone);banklist.add(bank);banklist.add(cvv);
                            Datas_nocardback datas = new Datas_nocardback();
                            if (isxinyongka == true) {
                                datas.setCardtype("0");
                            } else {
                                datas.setCardtype("1");
                            }
                            datas.setName(name);
                            datas.setSfz(sfz);
                            datas.setCardno(cardno);
                            datas.setPhone(phone);
                            datas.setBank(bank);
                            datas.setCvv(cvv);
                            datas.setValidthru(youxiaoqi + youxiaoqi1);
//							intent.putExtra("chongzhi1", banklist);
//							setResult(92,intent);
                            EventBus.getDefault().post(datas);
                            finish();
//							banklist.add(name);banklist.add(sfz);banklist.add(cardno);
//							banklist.add(phone);banklist.add(bank);banklist.add(cvv);//���֣����֤�����ţ��绰���������
//							Intent intent = new Intent();

                        } else if (czhiortxian.equals("chongzhi1")) {//�а���ù㲥
//							banklist.add(name);banklist.add(sfz);banklist.add(cardno);
//							banklist.add(phone);banklist.add(bank);banklist.add(cvv);//���֣����֤�����ţ��绰���������

                            Datas_nocardback datas = new Datas_nocardback();
                            if (isxinyongka == true) {
                                datas.setCardtype("0");
                            } else {
                                datas.setCardtype("1");
                            }
                            datas.setName(name);
                            datas.setSfz(sfz);
                            datas.setCardno(cardno);
                            datas.setPhone(phone);
                            datas.setBank(bank);
                            datas.setCvv(cvv);
                            datas.setValidthru(youxiaoqi + youxiaoqi1);
//							intent.putExtra("chongzhi1", banklist);
//							setResult(92,intent);
                            EventBus.getDefault().post(datas);
                            finish();

//							Intent intent = new Intent();
//							intent.setAction("com.woke.chongzhi");
//							intent.putExtra("chongzhi1", banklist);
//							sendBroadcast(intent);
//							finish();
                        } else if (czhiortxian.equals("tixian")) {//����ʱ��û�󶨹�
                            Log.e("9", "-ss");
                            banklist.add(name);
                            banklist.add(sfz);
                            banklist.add(cardno);
                            banklist.add(phone);
                            banklist.add(bank);
                            banklist.add("");//���֣����֤�����ţ��绰���������
//							intent.setClass(MywalletcardActivity.this, Tixian1Activity.class);
                            intent.putExtra("tixian1", banklist);
//							startActivity(intent);
                            setResult(96, intent);
                            finish();
                        } else if (czhiortxian.equals("tixian1")) {//����ʱ���а��
                            Log.e("9s", "-sds");
                            banklist.add(name);
                            banklist.add(sfz);
                            banklist.add(cardno);
                            banklist.add(phone);
                            banklist.add(bank);
                            banklist.add("");//���֣����֤�����ţ��绰���������
                            Intent intent = new Intent();
                            intent.setAction("com.woke.tixian");
                            intent.putExtra("tixian1", banklist);
                            sendBroadcast(intent);
                            finish();
                        } else if (czhiortxian.equals("nocarpay")) {//�޿�֧��ʱ
                            Datas_nocardback datas = new Datas_nocardback();
                            if (isxinyongka == true) {
                                datas.setCardtype("0");
                            } else {
                                datas.setCardtype("1");
                            }
                            datas.setName(name);
                            datas.setSfz(sfz);
                            datas.setCardno(cardno);
                            datas.setPhone(phone);
                            datas.setBank(bank);
                            datas.setCvv(cvv);
                            datas.setValidthru(youxiaoqi + youxiaoqi1);
//							banklist.add(name);banklist.add(sfz);banklist.add(cardno);
//							banklist.add(phone);banklist.add(bank);banklist.add(cvv);//���֣����֤�����ţ��绰���������
//							Intent intent = new Intent();
                            EventBus.getDefault().post(datas);
//							intent.setAction("com.woke.mywalletnocarpay");
//							intent.putExtra("nocarpay", banklist);
////							Log.e("cardno", "cardno"+cardno);
//							sendBroadcast(intent);
                            finish();
                        } else {
                            setResult(14, intent);
                            finish();
                        }
                    }else {
                        String tishi=response.getString("info") ;
                        if (response.has("data")) {
                            tishi = response.getJSONObject("data").getJSONObject("data").getString("msg");
                        }
                        tishi(tishi);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(MywalletcardActivity.this, "数据失败！",
                        Toast.LENGTH_SHORT).show();
                Log.e("绑卡", "失败" + responseString);
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
                mBar.setVisibility(View.VISIBLE);
                mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
                mTok.setClickable(false);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mBar.setVisibility(View.GONE);
                mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
                mTok.setClickable(true);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {


            case R.id.avmywalletcard_image_back:
                finish();
                break;

            case R.id.avmywalletcard_blind_yepaymore:
//                Toast.makeText(MywalletcardActivity.this, "这里做易宝选银行卡", Toast.LENGTH_SHORT).show();
                break;

            case R.id.avmywalletcard_blind_ok:
                Random rad = new Random();
                int nextInt = rad.nextInt(100);
                times = DateUtil.getTimess1() + nextInt;

                String name = mEname.getText().toString().trim();
                String sfz = mEsfz.getText().toString().trim();
                String cardno = mEno.getText().toString().trim();
                String cvv = "" + mEcvv.getText().toString().trim();
                String youxiaoqi = "" + mEvalidthru.getText().toString().trim();
                String youxiaoqi1 = "" + mEvalidthru1.getText().toString().trim();
                String phone = mEphone.getText().toString().trim();
                String bank = "" + mTbank.getText().toString().trim();
                System.out.println(cardno);
                if (null == cardno || cardno.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "银行卡不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == name || name.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "名字不能为空", Toast.LENGTH_SHORT).show();
                } else if (null == sfz || sfz.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "身份证不能为空", Toast.LENGTH_SHORT).show();
                } else if (isxinyongka == true && cvv.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "信用卡背后3位数不能为空", Toast.LENGTH_SHORT).show();
                } else if (isxinyongka == true && youxiaoqi.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "信用卡有效期月份不能为空", Toast.LENGTH_SHORT).show();
                } else if (isxinyongka == true && youxiaoqi1.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "信用卡有效期年份不能为空", Toast.LENGTH_SHORT).show();
                } else if (phone == null || phone.equals("")) {
                    Toast.makeText(MywalletcardActivity.this, "预留手机号不能为空", Toast.LENGTH_SHORT).show();
                } else if (bank.equals("") && isxinyongka == false) {
                    Toast.makeText(MywalletcardActivity.this, "银行全称不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    bankcardto(name, sfz, cardno, cvv, youxiaoqi, youxiaoqi1, phone, bank);
                }
                break;

            default:
                break;
        }
    }
    public void tishi( String kll) {
        alertDialog = new AlertDialog.Builder(MywalletcardActivity.this).
                setTitle("提示").
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
}
